package com.lxk.concurrency.example.aqs;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 控制同步等待的线程数量
 * @author leong
 *
 */
public class CyclicBarrierExample2 {

	private static CyclicBarrier barrier = new CyclicBarrier(5);

	public static void main(String[] args) throws InterruptedException {
		ExecutorService executor = Executors.newCachedThreadPool();

		for (int i = 0; i < 10; i++) {
			final int threadNum = i;

			Thread.sleep(1000);

			executor.execute(() -> {

				try {
					race(threadNum);
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
	}

	private static void race(int threadNum) throws Exception {
		Thread.sleep(1000);
		System.out.println("ready:" + threadNum);

		// ？？？迷
		barrier.await(2000, TimeUnit.MICROSECONDS);
		System.out.println("continue:" + threadNum);
	}
}
